package com.hyacinth.forumbite.controller;

import com.hyacinth.forumbite.common.AppConfig;
import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.model.Message;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.MessageService;
import com.hyacinth.forumbite.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: Yun
 * @Date: 2025/5/26
 */
@RestController
@RequestMapping("/message")
@Tag(name = "站内信相关接口")
public class MessageController {
    @Resource
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @Operation(summary = "发送站内信")
    @Parameters({
            @Parameter(name = "receiveUserId", description = "接收者id"),
            @Parameter(name = "content", description = "私信内容")
    })
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request, @RequestParam("receiveUserId") Long receiveUserId, @RequestParam("content") String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 用户禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给自己发
        if (user.getId().equals(receiveUserId)) {
            return AppResult.failed(ResultCode.FAILED);
        }
        // 检查接收用户状态
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常");
        }
        Message message = new Message()
                .setContent(content)
                .setReceiveUserId(receiveUserId)
                .setPostUserId(user.getId());
        messageService.create(message);
        return AppResult.success();
    }

    @Operation(summary = "未读站内信数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        return AppResult.success(messageService.selectUnreadCount(user.getId()));
    }

    @Operation(summary = "查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        return AppResult.success(messageService.selectListByUserId(user.getId()));
    }

    @Operation(summary = "更改站内信为已读")
    @Parameters({
            @Parameter(name = "id", description = "站内信id"),
    })
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request, @RequestParam("id") @NonNull Long id) {
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED);
        }

        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (!user.getId().equals(message.getReceiveUserId())) {
            return AppResult.failed(ResultCode.FAILED);
        }
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @Operation(summary = "回复站内信")
    @Parameters({
            @Parameter(name = "repliedId", description = "要回复的站内信id"),
            @Parameter(name = "content", description = "要回复的站内信的内容")
    })
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request, @RequestParam("repliedId") @NonNull Long repliedId, @RequestParam("content") String content) {
        Message existsMessage = messageService.selectById(repliedId);
        // 检查回复站内信是否存在
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED);
        }
        // 检查用户是否被禁言
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 检查回复站内信 接收者是不是自己
        if (existsMessage.getPostUserId().equals(user.getId())) {
            return AppResult.failed(ResultCode.FAILED);
        }
        Message message = new Message()
                .setContent(content)
                .setPostUserId(user.getId())
                .setReceiveUserId(existsMessage.getPostUserId());
        messageService.reply(repliedId, message);
        return AppResult.success();
    }
}
